package com.jojo.android.zxlib.tool;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建者 zx
 * 创建时间 2020/9/28 11:25
 */
public class ZxDownloadTool {
    private static final String TAG = "ZxDownloadTool";


    /**
     * 下载文件
     * @param url
     * @param dirPath
     * @param progress
     */
    public static void DownloadFile(final String url, final String dirPath, final ProgressListener progress) {
        final ProgressResponseBody.ProgressListener progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                progress.onProgress(contentLength, bytesRead);
            }
        };
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response = chain.proceed(chain.request());
                        //这里将ResponseBody包装成我们的ProgressResponseBody
                        return response.newBuilder()
                                .body(new ProgressResponseBody(response.body(),progressListener))
                                .build();
                    }
                })
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                progress.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream in = null;
                FileOutputStream fileOutputStream = null;
                File file = null;
                long fileLength = 0;
                long currLength = 0;
                try {
                    if (!ZxFileTool.isSDCardEnable()) {
                        progress.onFailure("外部储存卡不可访问");
                        return;
                    }
                    String suffix = url.substring(url.lastIndexOf('.'));
                    String fileName = ZxFileTool.getCacheFileNameFromUrl(url) + suffix;
                    File dir = new File(dirPath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    file = new File(dir, fileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileLength = response.body().contentLength();
                    in = response.body().byteStream();
                    fileOutputStream = new FileOutputStream(file);
                    byte[] b = new byte[1024 * 50];
                    int temp = 0;
                    while ((temp = in.read(b)) != -1) {
                        fileOutputStream.write(b, 0, temp);
                        currLength += temp;
//                        progress.onProgress(fileLength, currLength);
                    }
                    fileOutputStream.flush();
                    progress.onComplete(file.getAbsolutePath());
                } catch (Exception e) {
                    progress.onFailure(e.getMessage());
                } finally {
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fileOutputStream != null) {
                            fileOutputStream.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    public interface ProgressListener {
        void onProgress(long totalBytes, long remainingBytes);

        void onFailure(String msg);

        void onComplete(String filePath);
    }

}
